<?php

//
// +---------------------------------------------------------+
// | 开发组
// +---------------------------------------------------------+
// | Copyrigh  (c)  2020 The PHP Group
// +---------------------------------------------------------+
// | 商户 代理商
// +---------------------------------------------------------+
// | zxc
// | php后端开发
// |
// +———————————————————+
//

namespace App\Models\Admin;

use App\Tools\Financial;
use App\Tools\Prstatic;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class StockOrder extends Model
{

    protected $table = 'stock_order';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    /**
     * 获取列表
     * @param $where
     * @param int $limit
     * @return mixed
     */
    public static function getPageList($where, $limit = 15)
    {
        $data = [];
        if ($where['order_sn']) {
            $data[] = ['o.order_sn', '=', $where['order_sn']];
        }
        if ($where['tracking_number']) {
            $data[] = ['o.tracking_number', '=', $where['tracking_number']];
        }
        if ($where['store_id']) {
            $data[] = ['s.id', '=', $where['store_id']];
        }
        if ($where['type']) {
            $data[] = ['o.type', '=', $where['type']];
        }
        $start = $where['start_time'] ? strtotime($where['start_time']) : 0;
        $end = $where['end_time'] ? strtotime($where['end_time']) : time();
        $db = self::from('stock_order as o')
            ->select(['o.*', 's.store_name', 's.discount_rate'])
            ->leftJoin('store as s', 's.id', '=', 'o.store_id')
            ->where($data)->whereBetween('o.created_at', [$start, $end])
            ->orderBy('o.id', 'desc');
        if ($limit == 0) {
            $list = $db->get();
        } else {
            $list = $db->paginate($limit);
        }
        foreach ($list as $key => $vv) {
            $list[$key]['status_name'] = Prstatic::$stockStatus[$vv['status']];
        }
        return $list;
    }

    /**
     * 获取信息
     * @param $id
     */
    public static function getInfoById($id)
    {
        $info = self::where(['id' => $id])->first();
        if ($info) {
            $info = $info->toArray();
            $info['goods_list'] = $info['goods_list'] ? json_decode($info['goods_list'], true) : [];
            $info['status_name'] = Prstatic::$stockStatus[$info['status']];
            return $info;
        }
        return [];
    }


    public static function getBaseStockOrderList($storeId,$goodsId)
    {
        $db = self::from('stock_order as o')
            ->select(['o.store_name','o.order_sn','o.store_id', 'o.store_product_batch'])
            ->leftJoin('stock_order_goods as s', 's.order_id', '=', 'o.id')
            ->where( ['s.store_id', '=', $storeId]) ->where(['s.goods_id', '=', $goodsId])->where('o.status', '>', 0)
            ->orderBy('o.id', 'desc');
        $list = $db->first();
        return self::select(['id', 'order_sn','store_name', 'discount_rate'])->where('status', '>', 0)->get();
    }

    /**
     * 添加入库单信息  后台
     */
    public static function enterInfoByAdmin($data)
    {
        $goodsList = $data['goods'];
        if ($goodsList) {
            $time = time();
            $totalNum = 0;
            $totalMoney = 0;
            foreach ($goodsList as $kk => $vv) {
                $totalNum += $vv['goods_number'];
                $totalMoney += $vv['goods_price'] * $vv['goods_number'];
            }
            $info['order_sn'] = $data['order_sn'];
            $info['order_amount'] = $totalMoney;
            $info['goods_amount'] = $totalMoney;
            $info['goods_pay_amount'] = $totalMoney;
            $info['total_number'] = $totalNum;
            $info['remark'] = $data['remark'];
            $info['status'] = 1;
            $info['type'] = 2;
            $info['store_product_batch'] = $data['store_product_batch'];//商品入库批次
            $info['order_time'] = $time;
            $info['created_at'] = $time;
            $info['updated_at'] = $time;
            $info['create_user'] = $data['create_user'];
            $info['update_user'] = $data['create_user'];
            //            v($info);
            $order_id = self::insertGetId(array_filter($info));
            if ($order_id) {
                $dataArr = [];
                foreach ($goodsList as $kk => $vv) {
                    $tmpMoney = $vv['goods_price'] * $vv['goods_number'];
                    $dataArr['goods_id'] = $kk;
                    $dataArr['order_id'] = $order_id;
                    $dataArr['goods_number'] = $vv['goods_number'];
                    $dataArr['goods_price'] = $vv['goods_price'];
                    $dataArr['goods_amount'] = $tmpMoney;
                    $dataArr['created_at'] = $time;
                    $dataArr['create_user'] = $data['create_user'];
                    StockOrderGoods::insert(array_filter($dataArr));
                    GoodsRepertoryLog::addInfoByGoodsId($order_id, $kk, $vv['goods_number'], 0, 2, $data['create_user'], $data['order_sn'], $tmpMoney);
                }

                return $order_id;
            }
        }
        return false;
    }



    /**
     * 添加出库单信息  商户
     */
    public static function outInfoByOrder($data)
    {
        $orderSn = pdStoreSn('KC');
        $info['order_sn'] = $orderSn;
        $info['store_id'] = $data['store_id'];
        $info['order_name'] = $data['order_name'];
        $info['order_mobile'] = $data['order_mobile'];
        $info['order_province'] = $data['order_province'];
        $info['order_city'] = $data['order_city'];
        $info['order_area'] = $data['order_area'];
        $info['order_address'] = $data['order_address'];
        $info['order_amount'] = $data['order_amount'];
        $info['goods_amount'] = $data['goods_amount'];
        $info['goods_pay_amount'] = $data['goods_pay_amount'];
        $info['total_number'] = $data['total_number'];
        $info['tracking_number'] = $data['tracking_number'];
        $info['freight'] = $data['freight'];
        $info['express'] = $data['express'];
        $info['express_company'] = $data['express_company'];
        $info['remark'] = $data['remark'];
        $info['status'] = 1;
        $info['type'] = 1;
        $info['order_time'] = time();
        $info['created_at'] = time();
        $info['updated_at'] = time();
        $info['create_user'] = $data['create_user'];
        $info['update_user'] = $data['create_user'];
        $order_id = self::insertGetId(array_filter($info));
        if ($order_id) {
            // 扣款
            // 验证余额
            $is_storeYzMoney = Redis::GET('DEFAULT:storeYzMoney');
            if ($is_storeYzMoney == 1) {
                Financial::changeMoneyByStore($data['store_id'], $data['goods_pay_amount'], $data['freight'], $order_id);
            }
            $goodsList = StoreOrderGoods::getListByOid($data['id']);
            if ($goodsList) {
                $dataArr = [];
                foreach ($goodsList as $kk => $vv) {
                    $tmpMoney = $vv['goods_amount'];
                    $dataArr['goods_id'] = $vv['goods_id'];
                    $dataArr['order_id'] = $order_id;
                    $dataArr['store_id'] = $data['store_id'];
                    $dataArr['goods_number'] = $vv['goods_number'];
                    $dataArr['goods_price'] = $vv['goods_price'];
                    $dataArr['goods_amount'] = $vv['goods_amount'];
                    $dataArr['is_give'] = $vv['is_give'];
                    $dataArr['created_at'] = time();
                    $dataArr['create_user'] = $data['create_user'];
                    StockOrderGoods::insert(array_filter($dataArr));
                    GoodsRepertoryLog::addInfoByGoodsId($order_id, $vv['goods_id'], $vv['goods_number'], $data['store_id'], 1, $data['create_user'], $orderSn, $tmpMoney);
                }
            }
            StoreOrder::where(['id' => $data['id']])->update(['stock_order_sn' => $orderSn]);
            return $order_id;
        }
        return false;
    }

    /**
     * 添加出库单 后台
     */
    public static function outInfoByAdmin($data)
    {
        $goodsList = $data['goods'];
        if ($goodsList) {
            $totalNum = 0;
            $totalMoney = 0;
            foreach ($goodsList as $kk => $vv) {
                $goods_sale_num = Goods::where(['id' => $vv['goods_id']])->value('goods_sale_num');
                if ($goods_sale_num < $vv['goods_number']) {
                    errorMsg("商品库存不足");
                }
                $totalNum += $vv['goods_number'];
                $totalMoney += $vv['goods_price'] * $vv['goods_number'];
            }
            // 运费
            $expressFee = Express::getExpressFee($data['express_id'], $totalNum, $totalMoney, $data['order_province']);
            // 验证余额
            $is_storeYzMoney = Redis::GET('DEFAULT:storeYzMoney');
            if ($is_storeYzMoney == 1) {
                $storeMoney1 = Financial::getInfoByAid($data['store_id'], 1, 2, 'money'); // 管理费
                $storeMoney2 = Financial::getInfoByAid($data['store_id'], 1, 1, 'money'); // 货款
                if (($totalMoney + $expressFee) > ($storeMoney1 + $storeMoney2)) {
                    errorMsg("商户余额不足，请进行充值");
                }
            }
            $info['order_sn'] = $data['order_sn'];
            $info['store_id'] = $data['store_id'];
            $info['order_name'] = $data['order_name'];
            $info['order_mobile'] = $data['order_mobile'];
            $info['order_province'] = $data['order_province'];
            $info['order_city'] = $data['order_city'];
            $info['order_area'] = $data['order_area'];
            $info['order_address'] = $data['order_address'];
            $info['order_amount'] = $totalMoney + $expressFee;
            $info['goods_amount'] = $totalMoney;
            $info['goods_pay_amount'] = $totalMoney;
            $info['total_number'] = $totalNum;
            $info['tracking_number'] = $data['tracking_number'];
            $info['freight'] = $expressFee;
            $info['express_id'] = $data['express_id'];
            $info['express'] = '快递';
            $info['express_company'] = Express::getNameById($data['express_id']);
            $info['remark'] = $data['remark'];
            $info['status'] = 1;
            $info['type'] = 1;
            $info['order_time'] = time();
            $info['created_at'] = time();
            $info['updated_at'] = time();
            $info['create_user'] = $data['create_user'];
            $info['update_user'] = $data['create_user'];
            //            v($info);
            $order_id = self::insertGetId(array_filter($info));
            if ($order_id) {
                // 扣款
                if ($is_storeYzMoney == 1) {
                    Financial::changeMoneyByStore($data['store_id'], $totalMoney, $expressFee, $order_id);
                }
                $dataArr = [];
                foreach ($goodsList as $kk => $vv) {
                    $tmpMoney = $vv['goods_price'] * $vv['goods_number'];
                    $dataArr['goods_id'] = $kk;
                    $dataArr['order_id'] = $order_id;
                    $dataArr['store_id'] = $data['store_id'];
                    $dataArr['goods_number'] = $vv['goods_number'];
                    $dataArr['goods_price'] = $vv['goods_price'];
                    $dataArr['goods_amount'] = $tmpMoney;
                    $dataArr['created_at'] = time();
                    $dataArr['create_user'] = $data['create_user'];
                    StockOrderGoods::insert(array_filter($dataArr));
                    GoodsRepertoryLog::addInfoByGoodsId($order_id, $kk, $vv['goods_number'], $data['store_id'], 1, $data['create_user'], $data['order_sn'], $tmpMoney);
                }
                return $order_id;
            }
        }
        return false;
    }

    /**
     * 出库单
     * @param $data
     */
    public
    static function outInfo($data)
    {
    }
}
